package com.ruoyi.web.controller.auth;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author mr.huang [jie88888822@163.com]
 * @devTime 2022-06-15
 */
@Component
public class GiteeService {
	@Resource
	HHJGiteeOauth hhjGiteeOauth;

	@Resource
	RestTemplate restTemplate;

	public String authorizeUri() {
		return hhjGiteeOauth.authorize();
	}

	public String getAccessToken(String code) {
		String token = hhjGiteeOauth.accessToken(code);
		ResponseEntity<Object> entity = restTemplate.postForEntity(token, httpEntity(), Object.class);
		Object body = entity.getBody();
		assert body != null;
		String string = body.toString();
		String[] split = string.split("=");
		String accessToken = split[1].toString().split(",")[0];
		return accessToken;
	}

	public JSONObject getUserInfo(String accessToken) {
		String userInfo = hhjGiteeOauth.userInfo(accessToken);
		ResponseEntity<JSONObject> forEntity = restTemplate.exchange(userInfo, HttpMethod.GET, httpEntity(), JSONObject.class);
		JSONObject body = forEntity.getBody();
		return body;
	}

	public static HttpEntity httpEntity() {
		HttpHeaders headers = new HttpHeaders();
		headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");

		HttpEntity<HttpHeaders> request = new HttpEntity<>(headers);
		return request;
	}
}
